﻿#include "ecomsys.h"
#include <memory>
#include <algorithm>
#include <chrono>



string eComSys::centerText(const string& text) const {
		int padding = max(0ll, width - 2 - static_cast<int>(text.length())); // 确保 padding ≥ 0
		int left = padding / 2;
		int right = padding - left;
		return string(10, ' ') + text + string(right, ' ');
	}

	// 生成边框线
string eComSys::createDivider() const {
		return string(width, divider[0]);
	}


eComSys::eComSys(int w, std::string div, std::string p)
	: userManager("user.json"), productManager("product.json"), orderManager("order.json"),width(w) ,divider(div),prompt(p){
	userManager.readInAlluser();
	productManager.readInAllProducts();
	orderManager.loadAllOrders();
}


eComSys::~eComSys() {
	//释放socket资源
	closesocket(udpSocket);
	WSACleanup();
}



//------------------------------------------------------------------------------------------
//多客户端请求
//------------------------------------------------------------------------------------------

// 获取客户端唯一标识
std::string eComSys::getClientKey(const sockaddr_in& addr) {
	char ip[INET_ADDRSTRLEN];
	inet_ntop(AF_INET, &addr.sin_addr, ip, INET_ADDRSTRLEN);
	return std::string(ip) + ":" + std::to_string(ntohs(addr.sin_port));
}

// 通过用户名获取或创建客户端状态
ClientState& eComSys::getClientStateByUsername(const std::string& username, const sockaddr_in& addr) {
	auto it = usernameToClientState.find(username);
	if (it == usernameToClientState.end()) {
		ClientState newState;
		newState.address = addr;
		newState.lastActivity = std::time(nullptr);
		usernameToClientState[username] = newState;
		return usernameToClientState[username];
	}
	
	// 更新地址和活动时间
	it->second.address = addr;
	it->second.lastActivity = std::time(nullptr);
	return it->second;
}

// 通过client_id获取或创建客户端状态
ClientState& eComSys::getClientStateByClientId(const std::string& clientId, const sockaddr_in& addr) {
	// 首先查找是否已存在该client_id的客户端状态
	for (auto& [username, state] : usernameToClientState) {
		if (state.client_id == clientId) {
			// 更新地址和活动时间
			state.address = addr;
			state.lastActivity = std::time(nullptr);
			return state;
		}
	}
	
	// 如果不存在，创建一个新的客户端状态
	ClientState newState;
	newState.address = addr;
	newState.client_id = clientId;
	newState.lastActivity = std::time(nullptr);
	newState.isLoggedIn = false;
	
	// 使用client_id作为临时用户名存储
	std::string tempUsername = "temp_" + clientId;
	usernameToClientState[tempUsername] = newState;
	return usernameToClientState[tempUsername];
}

// 检查client_id是否已登录
bool eComSys::isClientLoggedIn(const std::string& clientId) {
	for (const auto& [username, state] : usernameToClientState) {
		if (state.client_id == clientId && state.isLoggedIn) {
			return true;
		}
	}
	return false;
}

// 通过client_id获取登录的用户名
std::string eComSys::getLoggedInUsernameByClientId(const std::string& clientId) {
	for (const auto& [username, state] : usernameToClientState) {
		if (state.client_id == clientId && state.isLoggedIn) {
			return state.loggedInUsername;
		}
	}
	return "";
}

// 强制登出指定client_id的所有登录
void eComSys::forceLogoutClient(const std::string& clientId) {
	for (auto& [username, state] : usernameToClientState) {
		if (state.client_id == clientId && state.isLoggedIn) {
			std::cout << "强制登出客户端: " << clientId << " (用户: " << state.loggedInUsername << ")" << std::endl;
			state.isLoggedIn = false;
			state.loggedInUsername = "";
		}
	}
	
}

// 通过用户名查找客户端地址
sockaddr_in* eComSys::getClientAddressByUsername(const std::string& username) {
	auto it = usernameToClientState.find(username);
	if (it != usernameToClientState.end()) {
		return &(it->second.address);
	}
	return nullptr;
}

// 更新用户名的客户端状态
void eComSys::updateClientState(const std::string& username, const sockaddr_in& addr, const std::string& userType) {
	auto it = usernameToClientState.find(username);
	if (it != usernameToClientState.end()) {
		it->second.address = addr;
		it->second.lastActivity = std::time(nullptr);
		if (!userType.empty()) {
			it->second.userType = userType;
		}
	} else {
		ClientState newState;
		newState.address = addr;
		newState.userType = userType;
		newState.lastActivity = std::time(nullptr);
		usernameToClientState[username] = newState;
	}
	
	std::cout << "更新客户端状态: " << username << " -> " << getClientKey(addr) << std::endl;
}

// 移除用户名的客户端状态
void eComSys::removeClientState(const std::string& username) {
	auto it = usernameToClientState.find(username);
	if (it != usernameToClientState.end()) {
		std::cout << "移除客户端状态: " << username << std::endl;
		usernameToClientState.erase(it);
	}
}

//暂时定为监听广播地址，8080端口
bool eComSys::initUDPSocket() {
	std::cout << "初始化UDP Socket..." << std::endl;
	
	if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
		std::cerr << "WSAStartup 失败，错误代码: " << WSAGetLastError() << std::endl;
		return false;
	}
	std::cout << "WSAStartup 成功" << std::endl;

	udpSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (udpSocket == INVALID_SOCKET) {
		std::cerr << "Socket 创建失败，错误代码: " << WSAGetLastError() << std::endl;
		WSACleanup();
		return false;
	}
	std::cout << "Socket 创建成功" << std::endl;

	// 设置socket选项
	int optval = 1;
	if (setsockopt(udpSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(optval)) == SOCKET_ERROR) {
		std::cout << "设置SO_REUSEADDR失败，错误代码: " << WSAGetLastError() << std::endl;
	}

	serverAddr.sin_family = AF_INET;
	serverAddr.sin_port = htons(8080);
	serverAddr.sin_addr.s_addr = INADDR_ANY;

	if (::bind(udpSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
		std::cerr << "Bind 失败，错误代码: " << WSAGetLastError() << std::endl;
		closesocket(udpSocket);
		WSACleanup();
		return false;
	}
	std::cout << "Bind 成功，监听端口 8080" << std::endl;

	// 设置非阻塞模式
	u_long mode = 1;
	if (ioctlsocket(udpSocket, FIONBIO, &mode) == SOCKET_ERROR) {
		std::cerr << "设置非阻塞模式失败，错误代码: " << WSAGetLastError() << std::endl;
		closesocket(udpSocket);
		WSACleanup();
		return false;
	}
	std::cout << "设置非阻塞模式成功" << std::endl;

	std::cout << "UDP Socket 初始化完成" << std::endl;
	return true;
}


void eComSys::runServer() {
	if (!initUDPSocket()) {
		std::cerr << "UDP服务器初始化失败" << std::endl;
		return;
	}

	std::cout << "UDP服务器启动成功，监听端口 8080" << std::endl;
	std::cout << "等待客户端连接..." << std::endl;

	char buffer[2048];
	sockaddr_in clientAddr;
	int addrLen = sizeof(clientAddr);
	int totalRequests = 0;
	int totalClients = 0;

	while (true) {
		// 定期清理超时客户端
		auto now = std::chrono::system_clock::now();
		auto timeout = std::chrono::minutes(30); // 30分钟超时
		int timeoutCount = 0;

		for (auto it = usernameToClientState.begin(); it != usernameToClientState.end(); ) {
			auto lastActive = std::chrono::system_clock::from_time_t(it->second.lastActivity);
			if (now - lastActive > timeout) {
				std::cout << "清理超时客户端: " << it->first << std::endl;
				it = usernameToClientState.erase(it);
				timeoutCount++;
			} else {
				++it;
			}
		}
		
		if (timeoutCount > 0) {
			std::cout << "清理了 " << timeoutCount << " 个超时客户端" << std::endl;
		}

		// 接收数据
		int result = recvfrom(udpSocket, buffer, sizeof(buffer), 0,
			(sockaddr*)&clientAddr, &addrLen);

		// 处理接收到的数据
		if (result > 0) {
			// 处理数据包
			processPacket(clientAddr, buffer, result);
			
			totalRequests++;
			
			// 每100个请求显示一次统计信息
			if (totalRequests % 100 == 0) {
				std::cout << "统计信息 - 总请求数: " << totalRequests 
						  << "，活跃用户数: " << usernameToClientState.size() << std::endl;
			}
		}
		else if (WSAGetLastError() != WSAEWOULDBLOCK) {
			int error = WSAGetLastError();
			std::cerr << " recvfrom 错误: " << error << std::endl;
			
			// 如果是严重错误，尝试重新初始化socket
			if (error == WSAENOTSOCK || error == WSAECONNRESET) {
				std::cout << "检测到socket错误，尝试重新初始化..." << std::endl;
				closesocket(udpSocket);
				Sleep(1000); // 等待1秒
				if (!initUDPSocket()) {
					std::cerr << " 重新初始化socket失败，退出服务器" << std::endl;
					break;
				}
				std::cout << " Socket重新初始化成功" << std::endl;
			}
		}

		// 其他处理...
		Sleep(10); // 避免CPU占用过高
	}
	
	std::cout << "👋 服务器已停止" << std::endl;
}

//根据消息类型进行处理,随时可以更改完善
void eComSys::processPacket(const sockaddr_in& clientAddr, const char* buffer, int len) {
	// 获取客户端标识
	std::string clientKey = getClientKey(clientAddr);
	
	// 记录接收到的数据
	std::cout << "收到来自 " << clientKey << " 的数据，大小: " << len << " 字节" << std::endl;
	
	// 解析JSON负载
	json request;
	try {
		request = json::parse(buffer, buffer + len);
		std::cout << "解析JSON成功: " << request.dump() << std::endl;
	}
	catch (const std::exception& e) {
		std::cout << "❌ JSON解析失败: " << e.what() << std::endl;
		json errorResponse;
		errorResponse["message"] = "Invalid JSON format";
		errorResponse["status"] = "error";
		sendResponse(clientAddr, errorResponse.dump());
		return;
	}
	catch (...) {
		std::cout << "❌ JSON解析失败: 未知错误" << std::endl;
		json errorResponse;
		errorResponse["message"] = "Invalid JSON format";
		errorResponse["status"] = "error";
		sendResponse(clientAddr, errorResponse.dump());
		return;
	}

	// 验证用户信息（对于需要登录的操作）
	std::string username;
	ClientState* clientState = nullptr;
	std::string clientId;
	
	if (request.contains("type")) {
		int type = request["type"].get<int>();
		bool requiresAuth = (type != MSG_LOGIN_REQUEST && type != MSG_SIGNIN_REQUEST && 
							type != MSG_DISPLAY_PRODUCTS_REQUEST && type != MSG_SEARCH_PRODUCTS_REQUEST &&
							type != MSG_DISPLAY_ACCOUNTS_REQUEST);
		
		if (requiresAuth) {
			if (!request.contains("username") || request["username"].get<std::string>().empty()) {
				std::cout << "需要登录的操作缺少用户名" << std::endl;
				json errorResponse;
				errorResponse["message"] = "Authentication required";
				errorResponse["status"] = "error";
				sendResponse(clientAddr, errorResponse.dump());
				return;
			}
			
			username = request["username"].get<std::string>();
			if (username == "guest") {
				std::cout << "游客用户不能执行此操作" << std::endl;
				json errorResponse;
				errorResponse["message"] = "Guest users cannot perform this operation";
				errorResponse["status"] = "error";
				sendResponse(clientAddr, errorResponse.dump());
				return;
			}
			
			// 验证用户是否存在
			if (users.find(username) == users.end()) {
				std::cout << "用户不存在: " << username << std::endl;
				json errorResponse;
				errorResponse["message"] = "User not found";
				errorResponse["status"] = "error";
				sendResponse(clientAddr, errorResponse.dump());
				return;
			}
			
			// 获取或创建客户端状态
			clientState = &getClientStateByUsername(username, clientAddr);
			
			// 检查序列号防重放（如果存在）
			if (request.contains("sequence_id")) {
				int sequenceId = request["sequence_id"].get<int>();
				if (sequenceId <= clientState->lastSequenceId) {
					std::cout << "检测到重复报文，序列号: " << sequenceId << std::endl;
					json errorResponse;
					errorResponse["message"] = "Duplicate packet detected";
					errorResponse["status"] = "error";
					sendResponse(clientAddr, errorResponse.dump());
					return;
				}
				clientState->lastSequenceId = sequenceId;
				std::cout << "序列号验证通过: " << sequenceId << std::endl;
			}
			
			// 更新客户端状态中的用户信息
			if (request.contains("user_type")) {
				clientState->userType = request["user_type"].get<std::string>();
			}
			
			std::cout << "用户验证通过: " << username << std::endl;
		}
	}

	// 验证时间戳（如果存在）
	if (request.contains("timestamp")) {
		time_t requestTime = request["timestamp"].get<time_t>();
		time_t currentTime = std::time(nullptr);
		if (std::abs(currentTime - requestTime) > 300) { // 5分钟时间差
			std::cout << "请求时间戳过期，时间差: " << std::abs(currentTime - requestTime) << " 秒" << std::endl;
			json errorResponse;
			errorResponse["message"] = "Request timestamp expired";
			errorResponse["status"] = "error";
			sendResponse(clientAddr, errorResponse.dump());
			return;
		}
		std::cout << "时间戳验证通过" << std::endl;
	}

	// 根据消息类型处理
	std::string responseData;
	
	if (request.contains("type")) {
		int type = request["type"].get<int>();
		std::cout << "处理消息类型: 0x" << std::hex << type << std::dec << std::endl;
		
		try {
			switch (type) {
			case MSG_LOGIN_REQUEST:
				responseData = logIn(request, clientAddr);
				break;
			case MSG_SIGNIN_REQUEST:
				responseData = signIn(request);
				break;
			case MSG_MAIN_MENU_REQUEST:
				responseData = MainMenu(request);
				break;
			case MSG_CONSUMER_MENU_REQUEST:
				responseData = consumerMenu(request);
				break;
			case MSG_SELLER_MENU_REQUEST:
				responseData = sellerMenu(request);
				break;
			case MSG_DISPLAY_PRODUCTS_REQUEST:
				responseData = displayProducts(request);
				break;
			case MSG_SEARCH_PRODUCTS_REQUEST:
				responseData = searchProducts(request);
				break;
			case MSG_ADD_PRODUCT_REQUEST:
				responseData = addProduct(request);
				break;
			case MSG_MANAGE_PRODUCTS_REQUEST:
				responseData = manageProducts(request);
				break;
			case MSG_DISPLAY_ACCOUNTS_REQUEST:
				responseData = displayAllAc(request);
				break;
			default:
				std::cout << "❌ 不支持的消息类型: 0x" << std::hex << type << std::dec << std::endl;
				json errorResponse;
				errorResponse["message"] = "Unsupported message type";
				errorResponse["status"] = "error";
				responseData = errorResponse.dump();
				break;
			}
		} catch (const std::exception& e) {
			std::cout << "❌ 处理请求时发生异常: " << e.what() << std::endl;
			json errorResponse;
			errorResponse["message"] = "处理请求时发生错误: " + std::string(e.what());
			errorResponse["status"] = "error";
			responseData = errorResponse.dump();
		} catch (...) {
			std::cout << "❌ 处理请求时发生未知异常" << std::endl;
			json errorResponse;
			errorResponse["message"] = "处理请求时发生错误";
			errorResponse["status"] = "error";
			responseData = errorResponse.dump();
		}
	} else {
		std::cout << "❌ 请求缺少消息类型" << std::endl;
		json errorResponse;
		errorResponse["message"] = "Missing message type";
		errorResponse["status"] = "error";
		responseData = errorResponse.dump();
	}

	std::cout << "发送响应给 " << clientKey << "，大小: " << responseData.size() << " 字节" << std::endl;
	sendResponse(clientAddr, responseData);
}



void eComSys::sendResponse(const sockaddr_in& clientAddr, const std::string& payload) {
	try {
		// 获取客户端标识用于日志
		std::string clientKey = getClientKey(clientAddr);
		
		// 发送数据
		int bytesSent = sendto(udpSocket, payload.data(), payload.size(), 0,
			(const sockaddr*)&clientAddr, sizeof(clientAddr));
		
		if (bytesSent == SOCKET_ERROR) {
			int error = WSAGetLastError();
			std::cout << "❌ 发送响应失败，客户端: " << clientKey 
					  << "，错误代码: " << error << std::endl;
		} else if (bytesSent != static_cast<int>(payload.size())) {
			std::cout << "⚠️ 发送响应不完整，客户端: " << clientKey 
					  << "，预期: " << payload.size() << " 字节，实际: " << bytesSent << " 字节" << std::endl;
		} else {
			std::cout << " 响应发送成功，客户端: " << clientKey 
					  << "，大小: " << bytesSent << " 字节" << std::endl;
		}
	} catch (const std::exception& e) {
		std::cout << "❌ 发送响应时发生异常: " << e.what() << std::endl;
	} catch (...) {
		std::cout << "❌ 发送响应时发生未知异常" << std::endl;
	}
}
//------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------



	// 添加菜单项
void eComSys:: addMainItem(const string& item) {
		mainitems.push_back(item);
	}

//=================================================================================
//商品菜单功能实现
//=================================================================================
//展示所有商品
std::string eComSys::displayProducts(const json& request) const {
	json response;
	
	// 检查请求是否包含用户名
	if (!request.contains("username")) {
		response["message"] = "请求缺少用户名";
		response["status"] = "error";
		return response.dump();
	}
	
	string username = request["username"].get<string>();
	
	// 验证用户名格式
	if (username.empty() || username.length() < 4 || username.length() > 12) {
		response["message"] = "用户名格式无效，长度需在4-12位之间";
		response["status"] = "error";
		return response.dump();
	}
	
	try {
		ostringstream oss;

		// 空数据提示
		if (products.empty()) {
			response["message"] = "\n当前没有商品可展示。\n";
			response["status"] = "success";
			return response.dump();
		}

		// 构建表头
		oss << "\n当前所有商品信息：\n"
			<< left
			<< setw(15) << "商户"
			<< setw(25) << "商品ID"
			<< setw(40) << "描述"
			<< setw(10) << "原价"
			<< setw(10) << "折扣"
			<< setw(10) << "税率"
			<< setw(10) << "现价"
			<< setw(6) << "库存\n"
			<< string(120, '-') << "\n";

		// 格式化商品数据
		for (const auto& [key, prod] : products) {
			const auto& [owner, id] = key;
			oss << left
				<< setw(15) << owner.substr(0, 14)  // 限制商户名称长度
				<< setw(25) << (" " + id + " ")     // 增加ID可视性
				<< setw(40) << prod->getDescription().substr(0, 39)  // 限制描述长度
				<< fixed << setprecision(2)
				<< setw(10) << prod->getOriginalPrice()
				<< setw(10) << prod->getDiscountRate()
				<< setw(10) << prod->getTaxRate()
				<< setw(10) << prod->getPrice()
				<< setw(6) << prod->getStock() << "\n";
		}

		// 返回商品数据
		response["message"] = oss.str();
		response["status"] = "success";
		response["total_products"] = products.size();
		
	} catch (const exception& e) {
		response["message"] = "系统错误: " + string(e.what());
		response["status"] = "error";
	} catch (...) {
		response["message"] = "发生未知错误";
		response["status"] = "error";
	}
	
	return response.dump();
}

//从所有商品里搜索
std::string eComSys::searchProducts(const json& request) const {
	json response;
	
	// 检查请求是否包含用户名
	if (!request.contains("username")) {
		response["message"] = "请求缺少用户名";
		response["status"] = "error";
		return response.dump();
	}
	
	string username = request["username"].get<string>();
	
	// 验证用户名格式
	if (username.empty() || username.length() < 4 || username.length() > 12) {
		response["message"] = "用户名格式无效，长度需在4-12位之间";
		response["status"] = "error";
		return response.dump();
	}
	
	try {
		// 获取搜索关键词
		string keyword = " ";
		if (request.contains("keyword")) {
			keyword = request["keyword"].get<string>();
		}
		
		// 获取价格范围
		double minPrice = 0, maxPrice = 0;
		if (request.contains("min_price") && request.contains("max_price")) {
			minPrice = request["min_price"].get<double>();
			maxPrice = request["max_price"].get<double>();
		}

		// 构建搜索结果
		ostringstream oss;
		oss << "\n搜索结果：\n"
			<< left
			<< setw(15) << "商户"
			<< setw(25) << "商品ID"
			<< setw(40) << "描述"
			<< setw(10) << "现价"
			<< setw(6) << "库存\n"
			<< string(95, '-') << "\n";

		bool hasResult = false;
		int resultCount = 0;
		
		for (const auto& [key, prod] : products) {
			const auto& [owner, id] = key;

			// 匹配逻辑
			bool nameMatch = (keyword == " ") ||
				(id.find(keyword) != string::npos ||
					prod->getDescription().find(keyword) != string::npos ||
					owner.find(keyword) != string::npos);

			bool priceMatch = (prod->getPrice() >= minPrice) &&
				(prod->getPrice() <= maxPrice) || (minPrice == 0 && maxPrice == 0);

			if (nameMatch && priceMatch) {
				hasResult = true;
				resultCount++;
				oss << left
					<< setw(15) << owner.substr(0, 14)
					<< setw(25) << (" " + id + " ")
					<< setw(40) << prod->getDescription().substr(0, 39)
					<< fixed << setprecision(2)
					<< setw(10) << prod->getPrice()
					<< setw(6) << prod->getStock() << "\n";
			}
		}

		// 处理无结果情况
		if (!hasResult) {
			oss << "\n未找到匹配商品\n";
		}

		// 返回搜索结果
		response["message"] = oss.str();
		response["status"] = "success";
		response["result_count"] = resultCount;
		response["keyword"] = keyword;
		response["min_price"] = minPrice;
		response["max_price"] = maxPrice;
		
	} catch (const exception& e) {
		response["message"] = "搜索错误: " + string(e.what());
		response["status"] = "error";
	} catch (...) {
		response["message"] = "发生未知错误";
		response["status"] = "error";
	}
	
	return response.dump();
}

std::string eComSys::addProduct(const json& request) {
	json response;
	
	// 检查请求是否包含用户名
	if (!request.contains("username")) {
		response["message"] = "请求缺少用户名";
		response["status"] = "error";
		return response.dump();
	}
	
	string username = request["username"].get<string>();
	
	// 验证用户名格式
	if (username.empty() || username.length() < 4 || username.length() > 12) {
		response["message"] = "用户名格式无效，长度需在4-12位之间";
		response["status"] = "error";
		return response.dump();
	}
	
	// 检查用户是否为商户
	auto it = users.find(username);
	if (it == users.end() || it->second->getUserType() != "seller") {
		response["message"] = "只有商户可以添加商品";
		response["status"] = "error";
		return response.dump();
	}
	
	try {
		// 检查必要字段
		if (!request.contains("product_id") || !request.contains("description") || 
			!request.contains("price") || !request.contains("stock") || !request.contains("product_type")) {
			response["message"] = "缺少必要字段：product_id, description, price, stock, product_type";
			response["status"] = "error";
			return response.dump();
		}
		
		string id = request["product_id"].get<string>();
		string desc = request["description"].get<string>();
		double price = request["price"].get<double>();
		int stock = request["stock"].get<int>();
		int type = request["product_type"].get<int>();
		
		// 验证商品ID
		ProductKey key = { username, id };
		if (products.count(key)) {
			response["message"] = "该商品ID已存在";
			response["status"] = "error";
			return response.dump();
		}
		
		// 验证描述长度
		if (desc.length() > 100) {
			desc = desc.substr(0, 100);
		}
		
		// 验证价格
		if (price < 0.01 || price > 1000000.0) {
			response["message"] = "价格必须在0.01-1000000之间";
			response["status"] = "error";
			return response.dump();
		}
		
		// 验证库存
		if (stock < 0 || stock > 9999) {
			response["message"] = "库存必须在0-9999之间";
			response["status"] = "error";
			return response.dump();
		}
		
		// 验证商品类型
		if (type < 1 || type > 3) {
			response["message"] = "商品类型必须是1-3";
			response["status"] = "error";
			return response.dump();
		}
		
		// 创建商品对象
		switch (type) {
		case 1: { // 图书
			double discount = 0.0;
			if (request.contains("discount_rate")) {
				discount = request["discount_rate"].get<double>();
				if (discount < 0.0 || discount > 1.0) {
					response["message"] = "折扣率必须在0-1之间";
					response["status"] = "error";
					return response.dump();
				}
			}
			products[key] = make_unique<Book>(username, id, desc, price, stock, discount);
			break;
		}
		case 2: { // 电子产品
			double discount = 0.0, tax = 0.0;
			if (request.contains("discount_rate")) {
				discount = request["discount_rate"].get<double>();
				if (discount < 0.0 || discount > 1.0) {
					response["message"] = "折扣率必须在0-1之间";
					response["status"] = "error";
					return response.dump();
				}
			}
			if (request.contains("tax_rate")) {
				tax = request["tax_rate"].get<double>();
				if (tax < 0.0 || tax > 1.0) {
					response["message"] = "税率必须在0-1之间";
					response["status"] = "error";
					return response.dump();
				}
			}
			products[key] = make_unique<Electronics>(username, id, desc, price, stock, discount, tax);
			break;
		}
		case 3: { // 服装
			double discount = 0.0;
			if (request.contains("discount_rate")) {
				discount = request["discount_rate"].get<double>();
				if (discount < 0.0 || discount > 1.0) {
					response["message"] = "折扣率必须在0-1之间";
					response["status"] = "error";
					return response.dump();
				}
			}
			products[key] = make_unique<Clothing>(username, id, desc, price, stock, discount);
			break;
		}
		}
		
		// 保存数据
		productManager.storeInProduct(*products[key]);
		
		response["message"] = "商品添加成功！";
		response["status"] = "success";
		response["product_id"] = id;
		response["product_type"] = type;
		
	} catch (const exception& e) {
		response["message"] = "添加商品错误: " + string(e.what());
		response["status"] = "error";
	} catch (...) {
		response["message"] = "发生未知错误";
		response["status"] = "error";
	}
	
	return response.dump();
}



// 实现商品管理功能
std::string eComSys::manageProducts(const json& request) {
	json response;
	
	// 检查请求中是否包含用户名
	if (!request.contains("username")) {
		response["message"] = "缺少用户名参数";
		response["status"] = "error";
		return response.dump();
	}
	
	std::string username = request["username"].get<std::string>();
	
	// 检查用户是否已登录
	auto it = usernameToClientState.find(username);
	if (it == usernameToClientState.end()) {
		response["message"] = "用户未登录";
		response["status"] = "error";
		return response.dump();
	}
	
	// 检查用户是否为商户
	auto userIt = users.find(username);
	if (userIt == users.end() || userIt->second->getUserType() != "seller") {
		response["message"] = "只有商户可以修改商品";
		response["status"] = "error";
		return response.dump();
	}
	
	
	try {
		// 收集当前商户商品
		vector<ProductKey> myProducts;
		for (const auto& [key, _] : products) {
			if (key.first == username) {
				myProducts.push_back(key);
			}
		}

		// 无商品处理
		if (myProducts.empty()) {
			response["message"] = "您尚未添加任何商品";
			response["status"] = "success";
			response["product_count"] = 0;
			return response.dump();
		}

		// 如果请求包含要修改的商品序号
		if (request.contains("product_index")) {
			int choice = request["product_index"].get<int>();
			if (choice < 1 || choice > myProducts.size()) {
				response["message"] = "无效的商品序号";
				response["status"] = "error";
				return response.dump();
			}
			
			ProductKey selectedKey = myProducts[choice - 1];
			if (!products.count(selectedKey)) {
				response["message"] = "商品不存在";
				response["status"] = "error";
				return response.dump();
			}
			auto& selectedProduct = products[selectedKey];
			
			// 如果请求包含修改操作
			if (request.contains("action")) {
				string action = request["action"].get<string>();
				
				if (action == "modify") {
					// 修改商品信息
					if (request.contains("modifications")) {
						json modifications = request["modifications"];
						bool hasChanges = false;
						
						// 修改描述
						if (modifications.contains("description")) {
							string desc = modifications["description"].get<string>();
							if (desc.length() > 100) {
								desc = desc.substr(0, 100);
							}
							selectedProduct->setDescription(desc);
							hasChanges = true;
						}
						
						// 修改原价
						if (modifications.contains("original_price")) {
							double price = modifications["original_price"].get<double>();
							if (price >= 0.01 && price <= 1000000.0) {
								selectedProduct->setOriginalPrice(price);
								hasChanges = true;
							} else {
								response["message"] = "价格必须在0.01-1000000之间";
								response["status"] = "error";
								return response.dump();
							}
						}
						
						// 修改库存
						if (modifications.contains("stock")) {
							int stock = modifications["stock"].get<int>();
							if (stock >= 0 && stock <= 9999) {
								selectedProduct->setStock(stock);
								hasChanges = true;
							} else {
								response["message"] = "库存必须在0-9999之间";
								response["status"] = "error";
								return response.dump();
							}
						}
						
						// 修改折扣率
						if (modifications.contains("discount_rate")) {
							double discount = modifications["discount_rate"].get<double>();
							if (discount >= 0.0 && discount <= 1.0) {
								if (auto book = dynamic_cast<Book*>(selectedProduct.get())) {
									book->setDiscountRate(discount);
									hasChanges = true;
								} else if (auto elec = dynamic_cast<Electronics*>(selectedProduct.get())) {
									elec->setDiscountRate(discount);
									hasChanges = true;
								} else if (auto cloth = dynamic_cast<Clothing*>(selectedProduct.get())) {
									cloth->setDiscountRate(discount);
									hasChanges = true;
								}
							} else {
								response["message"] = "折扣率必须在0-1之间";
								response["status"] = "error";
								return response.dump();
							}
						}
						
						// 修改税率（仅电子产品）
						if (modifications.contains("tax_rate")) {
							if (auto elec = dynamic_cast<Electronics*>(selectedProduct.get())) {
								double tax = modifications["tax_rate"].get<double>();
								if (tax >= 0.0 && tax <= 0.2) {
									elec->setTaxRate(tax);
									hasChanges = true;
								} else {
									response["message"] = "税率必须在0-0.2之间";
									response["status"] = "error";
									return response.dump();
								}
							} else {
								response["message"] = "只有电子产品可以设置税率";
								response["status"] = "error";
								return response.dump();
							}
						}
						
						if (hasChanges) {
							// 保存修改
							productManager.storeInProduct(*selectedProduct);
							response["message"] = "商品修改成功！";
							response["status"] = "success";
						} else {
							response["message"] = "没有进行任何修改";
							response["status"] = "success";
						}
					} else {
						response["message"] = "缺少修改参数";
						response["status"] = "error";
					}
				} else if (action == "delete") {
					// 删除商品
					products.erase(selectedKey);
					productManager.saveAllProducts();
					response["message"] = "商品删除成功！";
					response["status"] = "success";
				} else {
					response["message"] = "无效的操作类型";
					response["status"] = "error";
				}
			} else {
				// 返回商品详细信息
				ostringstream oss;
				oss << "\n当前商品信息：\n"
					<< "1. 描述: " << selectedProduct->getDescription() << "\n"
					<< "2. 原价: " << fixed << setprecision(2) << selectedProduct->getOriginalPrice() << "\n"
					<< "3. 库存: " << selectedProduct->getStock() << "\n";
				
				// 显示类型特有信息
				if (auto book = dynamic_cast<Book*>(selectedProduct.get())) {
					oss << "4. 折扣率: " << fixed << setprecision(2) << book->getDiscountRate() << "\n";
				} else if (auto elec = dynamic_cast<Electronics*>(selectedProduct.get())) {
					oss << "4. 折扣率: " << fixed << setprecision(2) << elec->getDiscountRate() << "\n"
						<< "5. 税率: " << fixed << setprecision(2) << elec->getTaxRate() << "\n";
				} else if (auto cloth = dynamic_cast<Clothing*>(selectedProduct.get())) {
					oss << "4. 折扣率: " << fixed << setprecision(2) << cloth->getDiscountRate() << "\n";
				}
				
				response["message"] = oss.str();
				response["status"] = "success";
			}
		} else {
			// 返回商品列表
			stringstream ss;
			ss << "您的商品列表：\n";
			for (int i = 0; i < myProducts.size(); i++) {
				auto& prod = products[myProducts[i]];
				ss << (i + 1) << ". " << prod->getDescription() 
				   << " (ID: " << prod->getProductID() << ")\n";
			}
			response["message"] = ss.str();
			response["status"] = "success";
			response["product_count"] = myProducts.size();
		}
		
	} catch (const exception& e) {
		response["message"] = "管理商品错误: " + string(e.what());
		response["status"] = "error";
	} catch (...) {
		response["message"] = "发生未知错误";
		response["status"] = "error";
	}
	
	return response.dump();
}




// 实现商品修改功能
std::string eComSys::modifyProduct(product* prod, const json& request) {
	json response;
	
	// 检查请求是否包含用户名
	if (!request.contains("username")) {
		response["message"] = "请求缺少用户名";
		response["status"] = "error";
		return response.dump();
	}
	
	string username = request["username"].get<string>();
	
	// 验证用户名格式
	if (username.empty() || username.length() < 4 || username.length() > 12) {
		response["message"] = "用户名格式无效，长度需在4-12位之间";
		response["status"] = "error";
		return response.dump();
	}
	
	// 检查用户是否已登录
	auto it = usernameToClientState.find(username);
	if (it == usernameToClientState.end()) {
		response["message"] = "用户未登录";
		response["status"] = "error";
		return response.dump();
	}
	
	// 检查用户是否为商户
	auto userIt = users.find(username);
	if (userIt == users.end() || userIt->second->getUserType() != "seller") {
		response["message"] = "只有商户可以修改商品";
		response["status"] = "error";
		return response.dump();
	}
	
	// 检查商品是否存在
	if (!prod) {
		response["message"] = "商品不存在";
		response["status"] = "error";
		return response.dump();
	}
	
	try {
		// 显示当前商品信息
		ostringstream oss;
		oss << "\n当前商品信息：\n"
			<< "1. 描述: " << prod->getDescription() << "\n"
			<< "2. 原价: " << fixed << setprecision(2) << prod->getOriginalPrice() << "\n"
			<< "3. 库存: " << prod->getStock() << "\n";
		
		// 显示类型特有信息
		if (auto book = dynamic_cast<Book*>(prod)) {
			oss << "4. 折扣率: " << fixed << setprecision(2) << book->getDiscountRate() << "\n";
		} else if (auto elec = dynamic_cast<Electronics*>(prod)) {
			oss << "4. 折扣率: " << fixed << setprecision(2) << elec->getDiscountRate() << "\n"
				<< "5. 税率: " << fixed << setprecision(2) << elec->getTaxRate() << "\n";
		} else if (auto cloth = dynamic_cast<Clothing*>(prod)) {
			oss << "4. 折扣率: " << fixed << setprecision(2) << cloth->getDiscountRate() << "\n";
		}
		
		response["current_info"] = oss.str();
		response["status"] = "success";
		
		// 处理修改请求
		if (request.contains("modifications")) {
			json modifications = request["modifications"];
			bool hasChanges = false;
			
			// 修改描述
			if (modifications.contains("description")) {
				string desc = modifications["description"].get<string>();
				if (desc.length() > 40) {
					desc = desc.substr(0, 40);
				}
				prod->setDescription(desc);
				hasChanges = true;
			}
			
			// 修改原价
			if (modifications.contains("original_price")) {
				double price = modifications["original_price"].get<double>();
				if (price >= 0.0 && price <= 1000000.0) {
					prod->setOriginalPrice(price);
					hasChanges = true;
				} else {
					response["message"] = "价格必须在0-1000000之间";
					response["status"] = "error";
					return response.dump();
				}
			}
			
			// 修改库存
			if (modifications.contains("stock")) {
				int stock = modifications["stock"].get<int>();
				if (stock >= 0 && stock <= 9999) {
					prod->setStock(stock);
					hasChanges = true;
				} else {
					response["message"] = "库存必须在0-9999之间";
					response["status"] = "error";
					return response.dump();
				}
			}
			
			// 修改折扣率
			if (modifications.contains("discount_rate")) {
				double discount = modifications["discount_rate"].get<double>();
				if (discount >= 0.0 && discount <= 1.0) {
					if (auto book = dynamic_cast<Book*>(prod)) {
						book->setDiscountRate(discount);
						hasChanges = true;
					} else if (auto elec = dynamic_cast<Electronics*>(prod)) {
						elec->setDiscountRate(discount);
						hasChanges = true;
					} else if (auto cloth = dynamic_cast<Clothing*>(prod)) {
						cloth->setDiscountRate(discount);
						hasChanges = true;
					}
				} else {
					response["message"] = "折扣率必须在0-1之间";
					response["status"] = "error";
					return response.dump();
				}
			}
			
			// 修改税率（仅电子产品）
			if (modifications.contains("tax_rate")) {
				if (auto elec = dynamic_cast<Electronics*>(prod)) {
					double tax = modifications["tax_rate"].get<double>();
					if (tax >= 0.0 && tax <= 0.2) {
						elec->setTaxRate(tax);
						hasChanges = true;
					} else {
						response["message"] = "税率必须在0-0.2之间";
						response["status"] = "error";
						return response.dump();
					}
				} else {
					response["message"] = "只有电子产品可以设置税率";
					response["status"] = "error";
					return response.dump();
				}
			}
			
			if (hasChanges) {
				// 保存修改
				productManager.saveAllProducts();
				
				// 显示更新后的商品信息
				ostringstream updatedOss;
				updatedOss << "商品信息已更新！\n\n更新后的商品信息：\n"
					<< "1. 描述: " << prod->getDescription() << "\n"
					<< "2. 原价: " << fixed << setprecision(2) << prod->getOriginalPrice() << "\n"
					<< "3. 库存: " << prod->getStock() << "\n";
				
				// 显示类型特有信息
				if (auto book = dynamic_cast<Book*>(prod)) {
					updatedOss << "4. 折扣率: " << fixed << setprecision(2) << book->getDiscountRate() << "\n";
				} else if (auto elec = dynamic_cast<Electronics*>(prod)) {
					updatedOss << "4. 折扣率: " << fixed << setprecision(2) << elec->getDiscountRate() << "\n"
						<< "5. 税率: " << fixed << setprecision(2) << elec->getTaxRate() << "\n";
				} else if (auto cloth = dynamic_cast<Clothing*>(prod)) {
					updatedOss << "4. 折扣率: " << fixed << setprecision(2) << cloth->getDiscountRate() << "\n";
				}
				
				response["message"] = updatedOss.str();
				response["status"] = "success";
			} else {
				response["message"] = "没有进行任何修改";
				response["status"] = "success";
			}
		}
		
	} catch (const exception& e) {
		response["message"] = "修改错误: " + string(e.what());
		response["status"] = "error";
	} catch (...) {
		response["message"] = "发生未知错误";
		response["status"] = "error";
	}
	
	return response.dump();
}

//=================================================================================
// 用户菜单功能实现
//=================================================================================
//注册
std::string eComSys::signIn(const json& request) {
	json response;
	
	// 获取请求参数
	std::string username = request["username"].get<std::string>();
	std::string password = request["password"].get<std::string>();
	std::string userType = request["user_type"].get<std::string>();
	
	// 检查是否要返回主菜单
	if (username == "0" || password == "0") {
		response["message"] = getMainMenuString();
		response["status"] = "success";
		
		// 如果用户名或密码为0，返回主菜单
		if (username == "0" && password == "0") {
			response["message"] = getMainMenuString();
			response["status"] = "success";
			response["type"] = "menu";
			return response.dump();
		}
	}
	
	// 验证用户名格式
	if (username.empty() || username.length() < 4 || username.length() > 12) {
		std::cout << "❌ 用户名格式无效: " << username << std::endl;
		response["message"] = "用户名格式无效，长度需在4-12位之间";
		response["status"] = "error";
		return response.dump();
	}
	
	// 验证密码格式
	if (password.empty() || password.length() < 6 || password.length() > 18) {
		std::cout << "❌ 密码格式无效，长度: " << password.length() << std::endl;
		response["message"] = "密码格式无效，长度需在6-18位之间";
		response["status"] = "error";
		return response.dump();
	}
	
	// 验证用户类型
	if (userType != "consumer" && userType != "seller") {
		std::cout << "❌ 无效的用户类型: " << userType << std::endl;
		response["message"] = "无效的用户类型，请选择 consumer 或 seller";
		response["status"] = "error";
		return response.dump();
	}
	
	// 检查用户是否已存在
	if (users.find(username) != users.end()) {
		std::cout << "❌ 用户已存在: " << username << std::endl;
		response["message"] = "用户已存在，请选择其他用户名";
		response["status"] = "error";
		return response.dump();
	}
	
	// 创建新用户
	std::unique_ptr<user> newUser;
	if (userType == "consumer") {
		newUser = std::make_unique<consumer>(username, password, "consumer");
	} else {
		newUser = std::make_unique<seller>(username, password, "seller");
	}
	
	// 添加到用户容器
	users[username] = std::move(newUser);
	
	// 保存到文件
	userManager.storeInuser(*users[username]);
	
	std::cout << "用户注册成功: " << username << " (类型: " << userType << ")" << std::endl;
	
	// 根据用户类型返回相应的菜单
	if (userType == "consumer") {
		response["message"] = consumerMenu(request);
		response["status"] = "success";
		response["type"] = "consumer_menu";
		response["user_type"] = "consumer";
	} else if (userType == "seller") {
		response["message"] = sellerMenu(request);
		response["status"] = "success";
		response["type"] = "seller_menu";
		response["user_type"] = "seller";
	}
	
	return response.dump();
}


std::string eComSys::displayAllAc(const json& request) const {
	json response;
	
	std::cout << "📋 显示所有账户信息" << std::endl;
	
	if (users.empty()) {
		std::cout << "ℹ️ 暂无用户账户" << std::endl;
		response["message"] = "暂无用户账户";
		response["status"] = "info";
		return response.dump();
	}
	
	std::stringstream ss;
	ss << "=== 所有用户账户 ===\n";
	ss << "总用户数: " << users.size() << "\n\n";
	
	for (const auto& pair : users) {
		const user& userObj = *pair.second;
		ss << "用户名: " << userObj.getId() << "\n";
		ss << "用户类型: " << userObj.getUserType() << "\n";
		ss << "账户余额: " << userObj.getAccountMoney() << "元\n";
		ss << "-------------------\n";
	}
	
	std::string result = ss.str();
	std::cout << "成功获取 " << users.size() << " 个用户账户信息" << std::endl;
	
	response["message"] = result;
	response["status"] = "success";
	response["type"] = "account_list";
	response["count"] = users.size();
	
	return response.dump();
}


//登录
std::string eComSys::logIn(const json& request, const sockaddr_in& clientAddr) {
	json response;
	
	// 获取请求参数
	std::string username = request["username"].get<std::string>();
	std::string password = request["password"].get<std::string>();
	std::string clientId = "";
	
	// 获取client_id（如果存在）
	if (request.contains("client_id")) {
		clientId = request["client_id"].get<std::string>();
	}
	
	// 检查是否要返回主菜单
	if (username == "0" || password == "0") {
		response["message"] = getMainMenuString();
		response["status"] = "success";
		response["type"] = "menu";
		return response.dump();
	}
	
	// 验证用户名和密码
	auto userIt = users.find(username);
	if (userIt == users.end()) {
		std::cout << "❌ 登录失败：用户不存在 - " << username << std::endl;
		response["message"] = "用户不存在，请先注册";
		response["status"] = "error";
		return response.dump();
	}
	
	if (!userIt->second->checkPassword(password)) {
		std::cout << "❌ 登录失败：密码错误 - " << username << std::endl;
		response["message"] = "密码错误，请重新输入";
		response["status"] = "error";
		return response.dump();
	}
	
	// 检查是否存在其他客户端使用相同用户名登录
	bool usernameAlreadyLoggedIn = false;
	std::string existingClientId = "";
	
	if (isUsernameLoggedIn(username)) {
		existingClientId = getClientIdByUsername(username);
		// 如果该用户名已被登录，检查是否是同一个客户端
		if (existingClientId != clientId) {
			usernameAlreadyLoggedIn = true;
		}
	}
	
	// 如果有client_id，进行单用户登录检查
	if (!clientId.empty()) {
		// 检查该client_id是否已登录其他用户
		std::string loggedInUser = getLoggedInUsernameByClientId(clientId);
		if (!loggedInUser.empty() && loggedInUser != username) {
			std::cout << "登录失败：客户端 " << clientId << " 已登录用户 " << loggedInUser << "，不能同时登录 " << username << std::endl;
			response["message"] = "客户端已登录其他用户，请先登出";
			response["status"] = "error";
			return response.dump();
		}
	}
	
	// 检查用户名是否已被其他客户端登录
	if (usernameAlreadyLoggedIn) {
		std::cout << "❌ 登录失败：用户 " << username << " 已被客户端 " << existingClientId << " 登录" << std::endl;
		response["message"] = "用户已被其他客户端登录，请先登出";
		response["status"] = "error";
		return response.dump();
	}
	
	// 登录成功
	// 更新客户端状态
	ClientState* clientState = nullptr;
	if (!clientId.empty()) {
		// 先创建或获取客户端状态
		clientState = &getClientStateByClientId(clientId, clientAddr);
		
		// 登录成功后更新客户端状态
		if (username != "0" && username != "guest") {
			// 强制登出该client_id的所有其他登录
			forceLogoutClient(clientId);
			if (request.contains("user_type")) {
				clientState->userType = request["user_type"].get<std::string>();
			} else {
				// 从用户对象获取用户类型
				auto userIt = users.find(username);
				if (userIt != users.end()) {
					clientState->userType = userIt->second->getUserType();
				}
			}
			
			std::cout << " 客户端 " << clientId << " 已绑定到用户 " << username << std::endl;
		}
		
		// 设置登录状态
		clientState->isLoggedIn = true;
		clientState->loggedInUsername = username;
	}
	
	std::string userType = userIt->second->getUserType();
	std::cout << "用户登录成功: " << username << " (类型: " << userType << ")";
	if (!clientId.empty()) {
		std::cout << " [客户端ID: " << clientId << "]";
	}
	std::cout << std::endl;
	
	// 根据用户类型返回相应的菜单
	if (userType == "consumer") {
		response["message"] = consumerMenu(request);
		response["status"] = "success";
		response["type"] = "consumer_menu";
		response["user_type"] = "consumer";
	} else if (userType == "seller") {
		response["message"] = sellerMenu(request);
		response["status"] = "success";
		response["type"] = "seller_menu";
		response["user_type"] = "seller";
	} else {
		response["message"] = "未知用户类型";
		response["status"] = "error";
	}
	
	return response.dump();
}





//=================================================================================
// 菜单
//=================================================================================
//展现给消费者的菜单
std::string eComSys::consumerMenu(const json& request) {
	// 如果请求包含选择，处理相应的操作
	if (request.contains("choice")) {
		try {
			int choice = request["choice"].get<int>();
			json response;
			
			// 检查请求中是否包含用户名
			if (!request.contains("username")) {
				response["message"] = "缺少用户名参数";
				response["status"] = "error";
				return response.dump();
			}
			
			std::string username = request["username"].get<std::string>();
			
			// 检查用户是否已登录
			auto it = usernameToClientState.find(username);
			if (it == usernameToClientState.end()) {
				response["message"] = "用户未登录";
				response["status"] = "error";
				return response.dump();
			}
			
			auto& currentUser = dynamic_cast<consumer&>(*users[username]);
			
			switch (choice) {
			case 1: { // 修改密码
				if (request.contains("old_password") && request.contains("new_password")) {
					string oldPwd = request["old_password"].get<string>();
					string newPwd = request["new_password"].get<string>();
					
					if (!currentUser.checkPassword(oldPwd)) {
						response["message"] = "密码错误！";
						response["status"] = "error";
					} else if (newPwd.length() < 6 || newPwd.length() > 18) {
						response["message"] = "密码不符合要求（6-18位字母数字组合）";
						response["status"] = "error";
					} else {
						currentUser.setPassword(newPwd);
						userManager.saveAllUsers();
						response["message"] = "密码修改成功！";
						response["status"] = "success";
					}
				} else {
					response["message"] = "缺少密码参数";
					response["status"] = "error";
				}
				break;
			}
			case 2: { // 查看余额
				response["message"] = "当前账户余额: " + std::to_string(currentUser.getAccountMoney()) + "元";
				response["status"] = "success";
				break;
			}
			case 3: { // 充值
				if (request.contains("amount")) {
					double amount = request["amount"].get<double>();
					if (amount <= 0) {
						response["message"] = "金额必须大于0";
						response["status"] = "error";
					} else {
						currentUser.recharge(amount);
						userManager.saveAllUsers();
						response["message"] = "充值成功！当前余额: " + std::to_string(currentUser.getAccountMoney()) + "元";
						response["status"] = "success";
					}
				} else {
					response["message"] = "缺少充值金额参数";
					response["status"] = "error";
				}
				break;
			}
			case 4: { // 查询密码（安全警告）
				response["message"] = "当前密码（安全提示：请勿泄露）: " + currentUser.getPsw();
				response["status"] = "success";
				break;
			}
			case 5: { // 浏览商品
				response["message"] = "浏览商品";
				response["status"] = "success";
				break;
			}
			case 6: { // 搜索商品
				response["message"] = "搜索商品";
				response["status"] = "success";
				break;
			}
			case 7: { // 添加商品到购物车
				// 检查必要字段
				if (!request.contains("owner") && !request.contains("product_owner") || !request.contains("product_id") || !request.contains("quantity")) {
					response["message"] = "缺少必要字段：owner/product_owner, product_id, quantity";
					response["status"] = "error";
					return response.dump();
				}
				
				// 获取owner字段，支持product_owner作为别名
				string owner;
				if (request.contains("owner")) {
					owner = request["owner"].get<string>();
				} else if (request.contains("product_owner")) {
					owner = request["product_owner"].get<string>();
				}
				
				string productID = request["product_id"].get<string>();
				int quantity = request["quantity"].get<int>();
				
				// 验证数量
				if (quantity <= 0 || quantity > 9999) {
					response["message"] = "购买数量必须在1-9999之间";
					response["status"] = "error";
					return response.dump();
				}
				
				// 检查商品是否存在
				ProductKey key = { owner, productID };
				if (!products.count(key)) {
					response["message"] = "商品不存在！";
					response["status"] = "error";
					return response.dump();
				}
				
				// 检查库存
				auto& product = products[key];
				if (product->getStock() < quantity) {
					response["message"] = "库存不足！当前库存: " + std::to_string(product->getStock());
					response["status"] = "error";
					return response.dump();
				}
				
				// 添加到购物车
				auto& cart = userCarts[username];
				cart.setConsumer(&currentUser);
				cart.addItem(key, quantity);
				
				response["message"] = "成功添加 " + std::to_string(quantity) + " 件商品到购物车";
				response["status"] = "success";
				response["product_description"] = product->getDescription();
				response["total_price"] = product->getPrice() * quantity;
				break;
			}
			case 8: { // 查看/管理购物车
				auto& cart = userCarts[username];
				auto items = cart.getItems();
				
				if (items.empty()) {
					response["message"] = "购物车为空！";
					response["status"] = "success";
					return response.dump();
				}
				
				// 构建购物车内容
				ostringstream oss;
				oss << "\n=== 购物车内容 ===\n";
				int index = 1;
				map<int, ProductKey> itemMap;
				double total = 0.0;
				
				for (auto& [key, qty] : items) {
					product* p = products[key].get();
					if (p) {
						double price = p->getPrice();
						double itemTotal = price * qty;
						oss << index << ". " << p->getDescription()
							<< " ×" << qty
							<< " 小计: " << fixed << setprecision(2) << itemTotal << "元\n";
						total += itemTotal;
						itemMap[index++] = key;
					}
				}
				oss << "总计: " << fixed << setprecision(2) << total << "元\n";
				
				response["message"] = oss.str();
				response["status"] = "success";
				response["total_amount"] = total;
				response["item_count"] = items.size();
				
				// 如果请求包含管理操作
				if (request.contains("action")) {
					string action = request["action"].get<string>();
					
					if (action == "modify_quantity" && request.contains("item_index") && request.contains("new_quantity")) {
						int itemIndex = request["item_index"].get<int>();
						int newQuantity = request["new_quantity"].get<int>();
						
						if (itemMap.count(itemIndex)) {
							ProductKey key = itemMap[itemIndex];
							if (newQuantity > 0) {
								// 检查库存
								auto& product = products[key];
								if (product->getStock() >= newQuantity) {
									cart.updateQuantity(key, newQuantity);
									response["message"] = "数量已修改";
									response["status"] = "success";
								} else {
									response["message"] = "库存不足！当前库存: " + std::to_string(product->getStock());
									response["status"] = "error";
								}
							} else {
								response["message"] = "数量无效";
								response["status"] = "error";
							}
						} else {
							response["message"] = "无效的商品序号";
							response["status"] = "error";
						}
					} else if (action == "remove_item" && request.contains("item_index")) {
						int itemIndex = request["item_index"].get<int>();
						
						if (itemMap.count(itemIndex)) {
							ProductKey key = itemMap[itemIndex];
							cart.removeItem(key);
							response["message"] = "商品已移除";
							response["status"] = "success";
						} else {
							response["message"] = "无效的商品序号";
							response["status"] = "error";
						}
					} else if (action == "clear_cart") {
						cart.clear();
						response["message"] = "购物车已清空";
						response["status"] = "success";
					} else {
						response["message"] = "无效的操作";
						response["status"] = "error";
					}
				}
				break;
			}
			case 9: { // 生成订单
				auto& cart = userCarts[username];
				if (cart.getItems().empty()) {
					response["message"] = "购物车为空，无法生成订单！";
					response["status"] = "error";
					return response.dump();
				}

				try {
					Order newOrder;
					newOrder.generateOrder(cart);
					cart.clear(); // 清空购物车
					orderManager.saveAllOrders();
					
					response["message"] = "订单生成成功！订单号：" + newOrder.getOrderId();
					response["status"] = "success";
					response["order_id"] = newOrder.getOrderId();
					response["total_amount"] = newOrder.calculateTotal();
					response["order_status"] = newOrder.getStatusString();
				}
				catch (const exception& e) {
					response["message"] = "订单生成失败: " + string(e.what());
					response["status"] = "error";
				}
				break;
			}
			case 10: { // 管理订单
				user* currentUser = users[username].get();
				vector<Order*> userOrders;
				//遍历所有该用户的历史订单
				for (const auto& [id, order] : allOrders) {
					if (order->getConsumer() == currentUser) {
						userOrders.push_back(order.get());
					}
				}

				if (userOrders.empty()) {
					response["message"] = "暂无订单！";
					response["status"] = "success";
					return response.dump();
				}
				// 构建订单列表
				ostringstream oss;
				oss << "\n=== 我的订单 ===\n";
				for (size_t i = 0; i < userOrders.size(); i++) {
					Order* o = userOrders[i];
					string status;
					switch (o->getStatus()) {
					case Order::Status::UNPAID: status = "未支付"; break;
					case Order::Status::PAID: status = "已支付"; break;
					case Order::Status::CANCELLED: status = "已取消"; break;
					}
					oss << i + 1 << ". 订单号: " << o->getOrderId()
						<< " | 状态: " << status
						<< " | 金额: " << fixed << setprecision(2) << o->calculateTotal() << "元\n";
				}
				
				response["message"] = oss.str();
				response["status"] = "success";
				response["order_count"] = userOrders.size();
				
				// 如果请求包含订单操作
				if (request.contains("order_action")) {
					string orderAction = request["order_action"].get<string>();
					
					if (orderAction == "pay_order" && request.contains("order_index")) {
						int orderIndex = request["order_index"].get<int>();
						
						if (orderIndex > 0 && orderIndex <= userOrders.size()) {
							Order* selected = userOrders[orderIndex - 1];
							
							if (selected->payOrder()) {
								orderManager.saveAllOrders();
								userManager.saveAllUsers(); // 保存用户余额变化
								response["message"] = "支付成功！";
								response["status"] = "success";
							} else {
								response["message"] = "支付失败（余额不足）！";
								response["status"] = "error";
							}
						} else {
							response["message"] = "无效的订单序号";
							response["status"] = "error";
						}
					} else if (orderAction == "cancel_order" && request.contains("order_index")) {
						int orderIndex = request["order_index"].get<int>();
						
						if (orderIndex > 0 && orderIndex <= userOrders.size()) {
							Order* selected = userOrders[orderIndex - 1];
							if (selected->getStatus() == Order::Status::UNPAID) {
								selected->cancelOrder();
								orderManager.saveAllOrders();
								response["message"] = "订单已取消！";
								response["status"] = "success";
							} else {
								response["message"] = "只能取消未支付订单";
								response["status"] = "error";
							}
						} else {
							response["message"] = "无效的订单序号";
							response["status"] = "error";
						}
					} else if (orderAction == "view_order_details" && request.contains("order_index")) {
						int orderIndex = request["order_index"].get<int>();
						
						if (orderIndex > 0 && orderIndex <= userOrders.size()) {
							Order* selected = userOrders[orderIndex - 1];
							
							ostringstream detailOss;
							detailOss << "\n=== 订单详情 ===\n";
							detailOss << "订单号: " << selected->getOrderId() << "\n";
							detailOss << "状态: " << selected->getStatusString() << "\n";
							detailOss << "总金额: " << fixed << setprecision(2) << selected->calculateTotal() << "元\n";
							
							response["message"] = detailOss.str();
							response["status"] = "success";
							response["order_id"] = selected->getOrderId();
							response["order_status"] = selected->getStatusString();
							response["total_amount"] = selected->calculateTotal();
						} else {
							response["message"] = "无效的订单序号";
							response["status"] = "error";
						}
					}
				}
				break;
			}
			case 11: { // 返回主菜单
				// 注销登录状态
				if (!username.empty()) {
					// 查找并清除该用户的登录状态
					for (auto& [existingUsername, state] : usernameToClientState) {
						if (state.loggedInUsername == username && state.isLoggedIn) {
							state.isLoggedIn = false;
							state.loggedInUsername = "";
							std::cout << " 用户 " << username << " 已注销登录" << std::endl;
							break;
						}
					}
					
					// 如果存在client_id，也清除对应的登录状态
					if (request.contains("client_id")) {
						std::string clientId = request["client_id"].get<std::string>();
						if (!clientId.empty()) {
							forceLogoutClient(clientId);
							std::cout << " 客户端 " << clientId << " 已注销登录" << std::endl;
						}
					}
				}
				
				response["message"] = getMainMenuString();
				response["status"] = "success";
				response["type"] = "menu";
				response["logout"] = true; // 标记已注销
				break;
			}
			default: {
				response["message"] = "无效选项，请重新选择！";
				response["status"] = "error";
				break;
			}
			}
			
			return response.dump();
		} catch (...) {
			json errorResponse;
			errorResponse["message"] = "处理请求时发生错误";
			errorResponse["status"] = "error";
			return errorResponse.dump();
		}
	}
	
	// 返回消费者菜单内容
	const vector<string> items = {
		"修改密码", "查看余额", "充值", "查询密码",
		"浏览商品", "搜索商品", "添加商品到购物车",
		"查看/管理购物车", "生成订单", "管理订单", "返回主菜单"
	};
	
	std::stringstream menuStream;
	menuStream << "\n" << createDivider() << "\n"
		<< centerText("消费者菜单") << "\n";

	for (size_t i = 0; i < items.size(); ++i) {
		menuStream << centerText(to_string(i + 1) + ". " + items[i]) << "\n";
	}

	menuStream << createDivider() << "\n"
		<< "请选择操作序号（1-" << items.size() << "）: ";
	
	json response;
	response["message"] = menuStream.str();
	response["status"] = "success";
	return response.dump();
}



std::string eComSys::sellerMenu(const json& request) {
	// 如果请求包含选择，处理相应的操作
	if (request.contains("choice")) {
		try {
			int choice = request["choice"].get<int>();
			json response;
			
			// 检查请求中是否包含用户名
			if (!request.contains("username")) {
				response["message"] = "缺少用户名参数";
				response["status"] = "error";
				return response.dump();
			}
			
			std::string username = request["username"].get<std::string>();
			
			// 检查用户是否已登录
			auto it = usernameToClientState.find(username);
			if (it == usernameToClientState.end()) {
				response["message"] = "用户未登录";
				response["status"] = "error";
				return response.dump();
			}
			
			auto& currentUser = dynamic_cast<seller&>(*users[username]);
			
			switch (choice) {
			case 1: { // 查看余额
				response["message"] = "当前账户余额: " + std::to_string(currentUser.getAccountMoney()) + "元";
				response["status"] = "success";
				break;
			}
			case 2: { // 充值
				if (request.contains("amount")) {
					double amount = request["amount"].get<double>();
					if (amount <= 0) {
						response["message"] = "金额必须大于0";
						response["status"] = "error";
					} else {
						currentUser.recharge(amount);
						userManager.saveAllUsers();
						response["message"] = "充值成功！当前余额: " + std::to_string(currentUser.getAccountMoney()) + "元";
						response["status"] = "success";
					}
				} else {
					response["message"] = "缺少充值金额参数";
					response["status"] = "error";
				}
				break;
			}
			case 3: { // 修改密码
				if (request.contains("old_password") && request.contains("new_password")) {
					string oldPwd = request["old_password"].get<string>();
					string newPwd = request["new_password"].get<string>();
					
					if (!currentUser.checkPassword(oldPwd)) {
						response["message"] = "密码错误！";
						response["status"] = "error";
					} else if (newPwd.length() < 6 || newPwd.length() > 18) {
						response["message"] = "密码不符合要求（6-18位字母数字组合）";
						response["status"] = "error";
					} else {
						currentUser.setPassword(newPwd);
						userManager.saveAllUsers();
						response["message"] = "密码修改成功！";
						response["status"] = "success";
					}
				} else {
					response["message"] = "缺少密码参数";
					response["status"] = "error";
				}
				break;
			}
			case 4: { // 查询密码（安全警告）
				response["message"] = "当前密码（安全提示：请勿泄露）: " + currentUser.getPsw();
				response["status"] = "success";
				break;
			}
			case 5: { // 商品管理
				return manageProducts(request);
			}
			case 6: { // 添加商品
				response["message"] = "进入添加商品";
				response["status"] = "success";
				break;
			}
			case 7: { // 浏览商品
				response["message"] = "浏览商品";
				response["status"] = "success";
				break;
			}
			case 8: { // 搜索商品
				response["message"] = "搜索商品";
				response["status"] = "success";
				break;
			}
			case 9: { // 返回主菜单
				// 注销登录状态
				if (!username.empty()) {
					// 查找并清除该用户的登录状态
					for (auto& [existingUsername, state] : usernameToClientState) {
						if (state.loggedInUsername == username && state.isLoggedIn) {
							state.isLoggedIn = false;
							state.loggedInUsername = "";
							std::cout << "🔓 用户 " << username << " 已注销登录" << std::endl;
							break;
						}
					}
					
					// 如果存在client_id，也清除对应的登录状态
					if (request.contains("client_id")) {
						std::string clientId = request["client_id"].get<std::string>();
						if (!clientId.empty()) {
							forceLogoutClient(clientId);
							std::cout << "🔓 客户端 " << clientId << " 已注销登录" << std::endl;
						}
					}
				}
				
				response["message"] = getMainMenuString();
				response["status"] = "success";
				response["type"] = "menu";
				response["logout"] = true; // 标记已注销
				break;
			}
			default: {
				response["message"] = "无效选项，请重新选择！";
				response["status"] = "error";
				break;
			}
			}
			
			return response.dump();
		} catch (...) {
			json errorResponse;
			errorResponse["message"] = "处理请求时发生错误";
			errorResponse["status"] = "error";
			return errorResponse.dump();
		}
	}
	
	// 返回商户菜单内容
	const vector<string> items = {
		"查看余额", "充值", "修改密码", "查询密码",
		"管理商品", "添加商品", "浏览商品", "搜索商品", "返回主菜单"
	};
	
	std::stringstream menuStream;
	menuStream << "\n" << createDivider() << "\n"
		<< centerText("商户菜单") << "\n";

	for (size_t i = 0; i < items.size(); ++i) {
		menuStream << centerText(to_string(i + 1) + ". " + items[i]) << "\n";
	}

	menuStream << createDivider() << "\n"
		<< "请选择操作序号（1-" << items.size() << "）: ";
	
	json response;
	response["message"] = menuStream.str();
	response["status"] = "success";
	return response.dump();
}


	// 返回主菜单字符串
std::string eComSys::getMainMenuString(){
	// 初始化菜单选项（只需一次）
	if (!if_init) {
		addMainItem("退出");
		addMainItem("登录");
		addMainItem("注册");
		addMainItem("查看所有账号信息");
		addMainItem("展示商品");
		addMainItem("搜索商品");
		if_init = 1;
	}
	
	// 构建菜单内容
	std::stringstream menuStream;
	menuStream << "\n       😍请选择操作序号！";
	if (!mainitems.empty()) {
		menuStream << "(1~" << mainitems.size() << ")";
	}
	menuStream << "\n" << createDivider() << "\n"
		<< centerText("") << "\n";  // 顶部留空
	
	for (size_t i = 0; i < mainitems.size(); ++i) {
		menuStream << centerText(to_string(i + 1) + "." + mainitems[i]) << "\n";
	}
	
	menuStream << centerText("") << "\n"  // 底部留空
		<< createDivider() << "\n";
	
	// 返回简单的JSON格式
	json response;
	response["message"] = menuStream.str();
	return response.dump();
}

// 处理主菜单请求
std::string eComSys::handleMainMenuRequest(const json& request) {
	// 初始化菜单选项（只需一次）
	if (!if_init) {
		addMainItem("退出");
		addMainItem("登录");
		addMainItem("注册");
		addMainItem("查看所有账号信息");
		addMainItem("展示商品");
		addMainItem("搜索商品");
		if_init = 1;
	}
	
	// 从请求中获取用户选择
	int choice = 1; // 默认值
	if (request.contains("choice")) {
		try {
			choice = request["choice"].get<int>();
		} catch (...) {
			json response;
			response["message"] = "无效的选择";
			response["status"] = "error";
			return response.dump();
		}
	}
	
	// 处理选项
	json response;
	switch (choice) {
	case SYSQUIT: {
		response["message"] = "正在退出系统...";
		response["status"] = "success";
		break;
	}
	case SYSLOGIN: {
		response["message"] = "进入登录流程";
		response["status"] = "success";
		break;
	}
	case SYSSIGNIN: {
		response["message"] = "进入注册流程";
		response["status"] = "success";
		break;
	}
	case SYSCHECKALL: {
		response["message"] = "查看所有账号信息";
		response["status"] = "success";
		break;
	}
	case 5: {
		response["message"] = "展示商品";
		response["status"] = "success";
		break;
	}
	case 6: {
		response["message"] = "搜索商品";
		response["status"] = "success";
		break;
	}
	default: {
		response["message"] = "无效选项，请重新选择！";
		response["status"] = "error";
		break;
	}
	}
	
	// 保存数据
	try {
		userManager.saveAllUsers();
		productManager.saveAllProducts();
	} catch (const exception& e) {
		response["message"] = "系统错误：数据保存失败";
		response["status"] = "error";
	}
	
	return response.dump();
}
// 显示完整菜单
std::string eComSys::MainMenu(const json& request) {
	// 如果请求包含"get_menu"字段，返回菜单字符串
	if (request.contains("get_menu") && request["get_menu"].get<bool>()) {
		return getMainMenuString();
	}
	
	// 否则处理菜单请求
	return handleMainMenuRequest(request);
}

// 检查用户名是否已被登录
bool eComSys::isUsernameLoggedIn(const std::string& username) {
	for (const auto& [existingUsername, state] : usernameToClientState) {
		if (state.loggedInUsername == username && state.isLoggedIn) {
			return true;
		}
	}
	return false;
}

// 获取用户名的登录客户端ID
std::string eComSys::getClientIdByUsername(const std::string& username) {
	for (const auto& [existingUsername, state] : usernameToClientState) {
		if (state.loggedInUsername == username && state.isLoggedIn) {
			return state.client_id;
		}
	}
	return "";
}



